﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Innova.Microfinanzas.BusinessEntities;
using Infragistics.Win.UltraMessageBox;
using MyCommerce.ManagementBase.Common.Base.Common;
using Infragistics.Win.UltraWinEditors;

namespace MyCommerce.ManagementBase.Common.Base.BaseEntities
{
    public class ContextEntity
    {
        private UltraMessageBoxInfo messageinfo = new UltraMessageBoxInfo();
        private UltraMessageBoxManager messageMgr = new UltraMessageBoxManager();

        public ContextEntity()
        {
            messageinfo.ShowHelpButton = Infragistics.Win.DefaultableBoolean.False;
            messageinfo.HeaderAppearance.TextHAlign = Infragistics.Win.HAlign.Left;
            messageinfo.ShowHelpButton = Infragistics.Win.DefaultableBoolean.False;
            messageinfo.FooterFormatted = @"<span style='font-weight:bold;'>My Commerce es una aplicación de los GLOBEX BOLIVIA. Derechos reservados </span>";
        }

        public long UserId
        {
            get;
            set;
        }

        public long EmployeeId
        {
            get;
            set;
        }

        public long DealerStoreId
        {
            get;
            set;
        }

        public long StoreId
        {
            get;
            set;
        }

        public BaseForm ParentForm
        {
            get;
            set;
        }


        public Command ObjCommandLoad
        {
            get;
            private set;
        }

        public List<Command> ColCommandsAvailable
        {
            get;
            set;
        }

        public Command GetCommand(string commandKey)
        {
            return ColCommandsAvailable.Find(objFilter => objFilter.CommandKey == commandKey);
        }

        public object InvoqueCommandWithParams(Command objCommand, object objParams, bool isModal)
        {
            object result = null;
            if (objCommand == null)
            {
                ShowInformationMessageBox("Usted no tiene permisos para ejecutar esta funcionalidad.", "Pantalla bloqueada");
                return null;
            }
            if (!String.IsNullOrEmpty(objCommand.Type))
            {
                string dlls = objCommand.Type;
                Type typeForm = Type.GetType(dlls, true);
                object formToShow = Activator.CreateInstance(typeForm);
                if (!ExistForm(objCommand))
                {
                    BaseForm objForm = formToShow as BaseForm;
                    InitializeFormControls(objForm);
                    objForm.Tag = objCommand;
                    objForm.Context = this;
                    objForm.Context.ObjCommandLoad = objCommand;
                    objForm.Text = objCommand.Title;                    
                    objForm.Parameter = objParams;
                    if (isModal)
                    {
                        objForm.StartPosition = FormStartPosition.CenterScreen;
                        objForm.ShowDialog();
                    }
                    else
                    {
                        objForm.MdiParent = ParentForm;
                        objForm.Show();
                    }
                    result = objForm.Result;
                }
            }
            return result;
        }

        public object InvoqueCommand(Command objCommand, bool isModal)
        {
            return InvoqueCommandWithParams(objCommand, null, isModal);
        }

        public void HandleException(Exception ex)
        {
            ShowErrorMessageBox(ex.Message, "Error en la aplicación");
        }

        public DialogResult ShowErrorMessageBox(string message, string title)
        {
            messageinfo.Caption = "Mensaje de error";
            messageinfo.Header = title;
            messageinfo.Text = message;
            messageinfo.Buttons = MessageBoxButtons.OK;
            messageinfo.Icon = MessageBoxIcon.Exclamation;
            return messageMgr.ShowMessageBox(messageinfo);
        }

        public DialogResult ShowInformationMessageBox(string message, string title)
        {
            messageinfo.Caption = "Mensaje";
            messageinfo.Header = title;
            messageinfo.Text = message;
            messageinfo.Buttons = MessageBoxButtons.OK;
            messageinfo.Icon = MessageBoxIcon.Information;
            return messageMgr.ShowMessageBox(messageinfo);
        }

        public DialogResult ShowQuestionMessageBox(string message, string title)
        {
            messageinfo.Caption = "Mensaje de confirmación";
            messageinfo.Header = title;
            messageinfo.Text = message;
            messageinfo.Buttons = MessageBoxButtons.YesNo;
            messageinfo.Icon = MessageBoxIcon.Question;
            return messageMgr.ShowMessageBox(messageinfo);
        }

        /// <summary>
        /// Busca el formulario enviado entre los abiertos, si esta abierto entonces lo pone visible.
        /// </summary>
        /// <param name="pForm">Formulario a buscar</param>
        /// <returns>True si existe el formulario, false si no existe</returns>
        private Boolean ExistForm(Command vCommand)
        {
            if (!vCommand.Multiple)
            {
                foreach (Form iForm in ParentForm.MdiChildren)
                {
                    if (((Command)iForm.Tag).CommandKey == vCommand.CommandKey)
                    {
                        iForm.Activate();
                        return true;
                    }
                }
            }
            return false;
        }

        private void InitializeFormControls(Form objForm)
        {
            if (objForm.Controls != null
                && objForm.Controls.Count > 0)
            {
                SetUpperCase(objForm.Controls);
            }
        }

        private void SetUpperCase(Control.ControlCollection colControls)        
        {
            if (colControls == null
                || colControls.Count == 0)
                return;
            else
            {
                foreach (Control objControl in colControls)
                {
                    if (objControl is UltraTextEditor)
                        ((UltraTextEditor)objControl).CharacterCasing = CharacterCasing.Upper;
                    if (objControl is TextBox)
                        ((TextBox)objControl).CharacterCasing = CharacterCasing.Upper;
                    SetUpperCase(objControl.Controls);
                }
            }
        }

        public static ContextEntity FindContext(Control controlToSearch)
        {
            return SearchContextRecursive(controlToSearch);
        }

        private static ContextEntity SearchContextRecursive(Control controlToSearch)
        {
            if (controlToSearch.Parent != null
                && controlToSearch.Parent is BaseForm)
            {
                return ((BaseForm)controlToSearch.Parent).Context;
            }
            else if (controlToSearch.Parent != null)
                return SearchContextRecursive(controlToSearch.Parent);
            else
                return new ContextEntity();
        }
    }
}
